// pages/snacksAdmin/index.js
const app = getApp();

Page({
  data: {
    // 学校和宿舍楼信息
    buildingList: [],
    selectedSchool: null,
    selectedBuilding: null,
    showBuildingModal: false,
    // 权限相关
    userPermissions: [], // 用户权限列表
    hasPermission: false, // 是否有权限
    
    // 标签页切换
    currentTab: 'products', // 'products' 或 'orders'
    
    // 零食商品列表
    snacksList: [],
    filteredSnacksList: [],
    searchKeyword: '',
    
    // 订单管理
    ordersList: [],
    filteredOrdersList: [],
    orderSearchKeyword: '',
    orderStatusFilter: 'all', // 'all', 'pending', 'delivering', 'completed'
    orderLoading: false,
    pendingOrdersCount: 0,
    
    // 编辑相关
    showEditModal: false,
    editSnack: null,
    editForm: {
      productName: '',
      price: '',
      stock: '',
      imgUrl: ''
    },
    editImageTemp: '', // 编辑时的临时图片路径
    
    // 状态
    loading: false,
    showAddModal: false,
    newSnackForm: {
      productName: '',
      price: '',
      stock: '',
      imgUrl: ''
    },
    
    // 退款相关
    showRefundModal: false,
    refundData: {
      orderId: '',
      totalAmount: 0,
      orderStatus: '',
      refundType: 'full',
      refundAmount: 0,
      refundReason: '',
      rejectReason: ''
    },
    newImageTemp: '', // 添加时的临时图片路径
    
    // 楼栋设置管理
    showSettingsModal: false,
    deliveryFee: 0,
    businessHours: '',
    buildingDeliveryFee: null, // 当前楼栋的配送费信息
    buildingBusinessHours: null // 当前楼栋的营业时间信息
  },

  onLoad(options) {
    console.log('snacksAdmin.onLoad', options);
    
    // 解析传递过来的参数
    if (options.param) {
      try {
        const param = JSON.parse(decodeURIComponent(options.param));
        console.log('snacksAdmin.onLoad2', param);
        const { schoolCode } = param;
        
        if (schoolCode) {
          this.setData({
            selectedSchool: schoolCode
          });
          
          // 先检查用户权限
          this.checkUserPermission(schoolCode);
        } else {
          wx.showToast({
            title: '缺少学校信息',
            icon: 'error'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      } catch (error) {
        console.error('解析参数失败:', error);
        wx.showToast({
          title: '参数错误',
          icon: 'error'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } else {
      wx.showToast({
        title: '缺少必要参数',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    if (this.data.selectedSchool && this.data.selectedBuilding) {
      if (this.data.currentTab === 'products') {
        this.loadSnacksList();
      } else if (this.data.currentTab === 'orders') {
        this.loadOrdersList();
      }
    }
  },

  // 检查用户权限
  checkUserPermission(schoolCode) {
    wx.showLoading({ title: '检查权限中...' });
    
    // 获取用户信息
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getUserInfoRequest: {}
      },
      success: (res) => {
        wx.hideLoading();
        console.log('getUserInfo result:', res);
        
        if (res.result?.code === 200) {
          const userInfo = res.result.data;
          
          // 检查是否有snackAdmin角色
          if (!userInfo.snackAdminPermission || !userInfo.roleType.includes('snackAdmin')) {
            wx.showModal({
              title: '权限不足',
              content: '您没有零食铺管理权限',
              showCancel: false,
              success: () => {
                wx.navigateBack();
              }
            });
            return;
          }
          
          // 检查是否有该学校的权限
          const snackPermissions = userInfo.snackAdminPermission || [];
          const schoolPermission = snackPermissions.find(permission => 
            permission.school_code === schoolCode
          );
          
          if (!schoolPermission) {
            wx.showModal({
              title: '权限不足',
              content: `您没有该学校的零食铺管理权限`,
              showCancel: false,
              success: () => {
                wx.navigateBack();
              }
            });
            return;
          }
          
          // 保存用户权限信息
          this.setData({
            userPermissions: snackPermissions,
            hasPermission: true
          });
          
          // 加载该学校的楼栋列表（会过滤权限）
          this.loadBuildingList(schoolCode);
          
        } else {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'error'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('getUserInfo failed:', err);
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'error'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    });
  },

  // 根据用户权限过滤楼栋列表
  filterBuildingsByPermission(buildings, schoolCode) {
    const userPermissions = this.data.userPermissions;
    const schoolPermission = userPermissions.find(permission => 
      permission.school_code === schoolCode
    );
    
    if (!schoolPermission || !schoolPermission.building_codes) {
      return [];
    }
    
    // 只返回用户有权限的楼栋
    return buildings.filter(building => 
      schoolPermission.building_codes.includes(building.buildingCode)
    );
  },

  // 检查用户是否有特定楼栋的权限
  checkBuildingPermission(buildingCode) {
    const schoolCode = this.data.selectedSchool;
    const userPermissions = this.data.userPermissions;
    const schoolPermission = userPermissions.find(permission => 
      permission.school_code === schoolCode
    );
    
    if (!schoolPermission || !schoolPermission.building_codes) {
      return false;
    }
    
    return schoolPermission.building_codes.includes(buildingCode);
  },

  // 加载宿舍楼列表
  loadBuildingList(schoolCode) {
    wx.showLoading({ title: '加载中' });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getBuildingListBySchoolAdminRequest: {
          schoolCode: schoolCode
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('getBuildingListBySchool result:', res);
        if (res.result?.code === 200) {
          const allBuildings = res.result.data.buildingList.map(item => ({
            buildingId: item.buildingCode,
            buildingName: item.buildingName,
            buildingCode: item.buildingCode
          }));
          
          // 根据用户权限过滤楼栋列表
          const filteredBuildings = this.filterBuildingsByPermission(allBuildings, schoolCode);
          
          if (filteredBuildings.length === 0) {
            wx.showModal({
              title: '权限不足',
              content: '您没有该学校任何楼栋的零食铺管理权限',
              showCancel: false,
              success: () => {
                wx.navigateBack();
              }
            });
            return;
          }
          
          this.setData({
            buildingList: filteredBuildings,
            showBuildingModal: true
          });
        } else {
          wx.showToast({
            title: '加载宿舍楼列表失败',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('getBuildingListBySchool failed:', err);
        wx.showToast({
          title: '加载宿舍楼列表失败',
          icon: 'error'
        });
      }
    });
  },

  // 选择宿舍楼
  onSelectBuilding(e) {
    const building = e.currentTarget.dataset.building;
    
    // 检查用户是否有该楼栋的权限
    if (!this.checkBuildingPermission(building.buildingCode)) {
      wx.showModal({
        title: '权限不足',
        content: `您没有${building.buildingName}的零食铺管理权限`,
        showCancel: false
      });
      return;
    }
    
    this.setData({
      selectedBuilding: building,
      showBuildingModal: false
    });
    
    // 加载该宿舍楼的零食商品列表
    this.loadSnacksList();
  },


  // 重新选择宿舍楼
  onReselectBuilding() {
    this.setData({
      selectedBuilding: null,
      snacksList: [],
      filteredSnacksList: []
    });
    this.loadBuildingList(this.data.selectedSchool);
  },


  // 关闭宿舍楼选择弹窗
  onCloseBuildingModal() {
    if (!this.data.selectedBuilding) {
      wx.showToast({
        title: '请先选择宿舍楼',
        icon: 'none'
      });
      return;
    }
    this.setData({
      showBuildingModal: false
    });
  },

  // 加载零食商品列表
  loadSnacksList() {
    if (!this.data.selectedSchool || !this.data.selectedBuilding) {
      return;
    }
    
    // 再次检查楼栋权限
    if (!this.checkBuildingPermission(this.data.selectedBuilding.buildingCode)) {
      wx.showModal({
        title: '权限不足',
        content: `您没有${this.data.selectedBuilding.buildingName}的零食铺管理权限`,
        showCancel: false,
        success: () => {
          wx.navigateBack();
        }
      });
      return;
    }
    
    this.setData({ loading: true });
    
    const schoolCode = this.data.selectedSchool;
    const buildingCode = this.data.selectedBuilding.buildingCode;
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getSnacksListForAdminRequest: {
          schoolCode: schoolCode,
          buildingCode: buildingCode,
          searchKeyword: this.data.searchKeyword
        }
      },
      success: (res) => {
        console.log('loadSnacksList result:', res);
        if (res.result?.code === 200) {
          const snacksList = res.result.data.snacksList || [];
          this.setData({
            snacksList,
            filteredSnacksList: snacksList
          });
        } else {
          wx.showToast({
            title: res.result?.message || '获取商品列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('loadSnacksList failed:', err);
        wx.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 搜索零食
  onSearchInput(e) {
    const keyword = e.detail.value.trim();
    this.setData({ searchKeyword: keyword });
    
    // 重新加载数据，包含搜索关键词
    this.loadSnacksList();
  },

  // 清空搜索
  onClearSearch() {
    this.setData({ 
      searchKeyword: ''
    });
    // 重新加载数据
    this.loadSnacksList();
  },

  // 上下架零食
  onToggleStatus(e) {
    const snackId = e.currentTarget.dataset.id;
    const snack = this.data.snacksList.find(s => s._id === snackId);
    if (!snack) return;
    
    const newStatus = snack.status === 'ON_SALE' ? 'OFF_SALE' : 'ON_SALE';
    const action = newStatus === 'ON_SALE' ? '上架' : '下架';
    
    wx.showModal({
      title: '确认操作',
      content: `确定要${action}这个商品吗？`,
      success: (res) => {
        if (res.confirm) {
          this.updateSnackStatus(snackId, newStatus);
        }
      }
    });
  },

  // 更新商品状态
  updateSnackStatus(snackId, status) {
    wx.showLoading({ title: '处理中...' });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        updateSnackStatusAdminRequest: {
          snackId: snackId,
          status: status
        }
      },
      success: (res) => {
        console.log('updateSnackStatus result:', res);
        if (res.result?.code === 200) {
          // 重新加载数据
          this.loadSnacksList();
          
          wx.showToast({
            title: status === 'ON_SALE' ? '上架成功' : '下架成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.result?.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('updateSnackStatus failed:', err);
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 编辑零食
  onEditSnack(e) {
    const snackId = e.currentTarget.dataset.id;
    const snack = this.data.snacksList.find(s => s._id === snackId);
    if (!snack) return;
    
    this.setData({
      editSnack: snack,
      editForm: {
        productName: snack.productName,
        price: snack.price,
        stock: snack.stock.toString(),
        imgUrl: snack.imgList && snack.imgList.length > 0 ? snack.imgList[0] : ''
      },
      editImageTemp: snack.imgList && snack.imgList.length > 0 ? snack.imgList[0] : '',
      showEditModal: true
    });
  },

  // 编辑表单输入
  onEditFormInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`editForm.${field}`]: value
    });
  },

  // 选择编辑图片
  async onSelectEditImage() {
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera']
      });

      const tempFilePath = res.tempFiles[0].tempFilePath;
      
      wx.showLoading({
        title: '上传中...',
        mask: true
      });

      // 生成唯一文件名
      const timestamp = Date.now();
      const randomStr = Math.random().toString(36).substring(2, 8);
      const fileName = `snack_${timestamp}_${randomStr}.jpg`;
      const cloudPath = `snacks-images/${fileName}`;

      // 上传到腾讯云存储
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath,
        filePath: tempFilePath
      });

      console.log('图片上传成功:', uploadResult);

      this.setData({
        editImageTemp: uploadResult.fileID,
        'editForm.imgUrl': uploadResult.fileID
      });

      wx.hideLoading();
      wx.showToast({
        title: '图片上传成功',
        icon: 'success'
      });

    } catch (err) {
      wx.hideLoading();
      console.error('选择或上传图片失败:', err);
      wx.showToast({
        title: '图片上传失败',
        icon: 'none'
      });
    }
  },

  // 删除编辑图片
  onDeleteEditImage() {
    this.setData({
      editImageTemp: '',
      'editForm.imgUrl': ''
    });
  },

  // 保存编辑
  onSaveEdit() {
    const { productName, price, stock } = this.data.editForm;
    const imgUrl = this.data.editImageTemp || '';
    
    // 表单验证
    if (!productName.trim()) {
      wx.showToast({ title: '请输入商品名称', icon: 'none' });
      return;
    }
    
    if (!price || isNaN(parseFloat(price)) || parseFloat(price) <= 0) {
      wx.showToast({ title: '请输入正确的价格', icon: 'none' });
      return;
    }
    
    if (!stock || isNaN(parseInt(stock)) || parseInt(stock) < 0) {
      wx.showToast({ title: '请输入正确的库存', icon: 'none' });
      return;
    }
    
    wx.showLoading({ title: '保存中...' });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        saveSnackAdminRequest: {
          snackId: this.data.editSnack._id,
          schoolCode: this.data.selectedSchool,
          buildingCode: this.data.selectedBuilding.buildingCode,
          subProductId: this.data.editSnack.subProductId,
          productName: productName.trim(),
          price: price.toString(),
          stock: parseInt(stock),
          imgList: imgUrl.trim() ? [imgUrl.trim()] : []
        }
      },
      success: (res) => {
        console.log('saveSnack result:', res);
        if (res.result?.code === 200) {
          this.onCloseEditModal();
          this.loadSnacksList(); // 重新加载列表
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.result?.message || '保存失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('saveSnack failed:', err);
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 关闭编辑弹窗
  onCloseEditModal() {
    this.setData({
      showEditModal: false,
      editSnack: null,
      editForm: {
        productName: '',
        price: '',
        stock: '',
        imgUrl: ''
      },
      editImageTemp: ''
    });
  },

  // 添加新零食
  onAddSnack() {
    this.setData({
      newSnackForm: {
        productName: '',
        price: '',
        stock: '',
        imgUrl: ''
      },
      newImageTemp: '',
      showAddModal: true
    });
  },

  // 新零食表单输入
  onNewSnackFormInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`newSnackForm.${field}`]: value
    });
  },

  // 选择新零食图片
  async onSelectNewImage() {
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera']
      });

      const tempFilePath = res.tempFiles[0].tempFilePath;
      
      wx.showLoading({
        title: '上传中...',
        mask: true
      });

      // 生成唯一文件名
      const timestamp = Date.now();
      const randomStr = Math.random().toString(36).substring(2, 8);
      const fileName = `snack_${timestamp}_${randomStr}.jpg`;
      const cloudPath = `snacks-images/${fileName}`;

      // 上传到腾讯云存储
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath,
        filePath: tempFilePath
      });

      console.log('图片上传成功:', uploadResult);

      this.setData({
        newImageTemp: uploadResult.fileID,
        'newSnackForm.imgUrl': uploadResult.fileID
      });

      wx.hideLoading();
      wx.showToast({
        title: '图片上传成功',
        icon: 'success'
      });

    } catch (err) {
      wx.hideLoading();
      console.error('选择或上传图片失败:', err);
      wx.showToast({
        title: '图片上传失败',
        icon: 'none'
      });
    }
  },

  // 删除新零食图片
  onDeleteNewImage() {
    this.setData({
      newImageTemp: '',
      'newSnackForm.imgUrl': ''
    });
  },

  // 保存新零食
  onSaveNewSnack() {
    const { productName, price, stock } = this.data.newSnackForm;
    const imgUrl = this.data.newImageTemp || '';
    
    // 表单验证
    if (!productName.trim()) {
      wx.showToast({ title: '请输入商品名称', icon: 'none' });
      return;
    }
    
    if (!price || isNaN(parseFloat(price)) || parseFloat(price) <= 0) {
      wx.showToast({ title: '请输入正确的价格', icon: 'none' });
      return;
    }
    
    if (!stock || isNaN(parseInt(stock)) || parseInt(stock) < 0) {
      wx.showToast({ title: '请输入正确的库存', icon: 'none' });
      return;
    }
    
    wx.showLoading({ title: '添加中...' });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        saveSnackAdminRequest: {
          snackId: '', // 新增时为空
          schoolCode: this.data.selectedSchool,
          buildingCode: this.data.selectedBuilding.buildingCode,
          subProductId: Date.now().toString(), // 使用时间戳作为子产品ID
          productName: productName.trim(),
          price: price.toString(),
          stock: parseInt(stock),
          imgList: imgUrl.trim() ? [imgUrl.trim()] : []
        }
      },
      success: (res) => {
        console.log('saveSnack result:', res);
        if (res.result?.code === 200) {
          this.onCloseAddModal();
          this.loadSnacksList(); // 重新加载列表
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.result?.message || '添加失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('saveSnack failed:', err);
        wx.showToast({
          title: '添加失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 关闭添加弹窗
  onCloseAddModal() {
    this.setData({
      showAddModal: false,
      newSnackForm: {
        productName: '',
        price: '',
        stock: '',
        imgUrl: ''
      },
      newImageTemp: ''
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadSnacksList();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 楼栋设置相关方法
  // 打开楼栋设置弹窗
  onOpenSettings() {
    if (!this.data.selectedBuilding) {
      wx.showToast({
        title: '请先选择宿舍楼',
        icon: 'none'
      });
      return;
    }
    
    // 加载当前楼栋的设置信息
    this.loadBuildingSettings();
  },

  // 加载楼栋设置信息
  loadBuildingSettings() {
    wx.showLoading({ title: '加载中...' });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getBuildingDeliveryFeeRequest: {
          schoolCode: this.data.selectedSchool,
          buildingCode: this.data.selectedBuilding.buildingCode
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('loadBuildingSettings result:', res);
        if (res.result?.code === 200) {
          const deliveryFee = res.result.data.deliveryFee || 0;
          const businessHours = res.result.data.businessHours || '';
          this.setData({
            deliveryFee: deliveryFee,
            businessHours: businessHours,
            buildingDeliveryFee: res.result.data,
            buildingBusinessHours: res.result.data,
            showSettingsModal: true
          });
        } else {
          wx.showToast({
            title: res.result?.message || '获取楼栋设置信息失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('loadBuildingSettings failed:', err);
        wx.showToast({
          title: '获取楼栋设置信息失败',
          icon: 'none'
        });
      }
    });
  },

  // 配送费输入
  onDeliveryFeeInput(e) {
    const value = e.detail.value;
    this.setData({
      deliveryFee: value
    });
  },

  // 营业时间输入
  onBusinessHoursInput(e) {
    const value = e.detail.value;
    this.setData({
      businessHours: value
    });
  },

  // 保存楼栋设置
  onSaveSettings() {
    const deliveryFee = parseFloat(this.data.deliveryFee);
    const businessHours = this.data.businessHours.trim();
    
    if (isNaN(deliveryFee) || deliveryFee < 0) {
      wx.showToast({
        title: '请输入正确的配送费',
        icon: 'none'
      });
      return;
    }
    
    if (!businessHours) {
      wx.showToast({
        title: '请输入用户须知',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '保存中...' });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        updateBuildingDeliveryFeeRequest: {
          schoolCode: this.data.selectedSchool,
          buildingCode: this.data.selectedBuilding.buildingCode,
          deliveryFee: deliveryFee,
          businessHours: businessHours
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('updateBuildingSettings result:', res);
        if (res.result?.code === 200) {
          wx.showToast({
            title: '楼栋设置保存成功',
            icon: 'success'
          });
          this.onCloseSettingsModal();
        } else {
          wx.showToast({
            title: res.result?.message || '设置失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('updateBuildingSettings failed:', err);
        wx.showToast({
          title: '设置失败',
          icon: 'none'
        });
      }
    });
  },

  // 关闭楼栋设置弹窗
  onCloseSettingsModal() {
    this.setData({
      showSettingsModal: false,
      deliveryFee: 0,
      businessHours: '',
      buildingDeliveryFee: null,
      buildingBusinessHours: null
    });
  },

  // 防止弹窗内点击冒泡
  noop() {},

  // ==================== 订单管理相关方法 ====================
  
  // 切换标签页
  onSwitchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tab });
    
    if (tab === 'orders' && this.data.selectedSchool && this.data.selectedBuilding) {
      this.loadOrdersList();
    }
  },

  // 加载订单列表
  loadOrdersList() {
    if (!this.data.selectedSchool || !this.data.selectedBuilding) {
      return;
    }
    
    this.setData({ orderLoading: true });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getSnacksOrdersForAdminRequest: {
          schoolCode: this.data.selectedSchool,
          buildingCode: this.data.selectedBuilding.buildingCode,
          searchKeyword: this.data.orderSearchKeyword,
          statusFilter: this.data.orderStatusFilter
        }
      },
      success: (res) => {
        console.log('loadOrdersList result:', res);
        if (res.result?.code === 200) {
          const ordersList = res.result.data.ordersList || [];
          const pendingCount = ordersList.filter(order => order.processStatus === '待配送').length;
          
          this.setData({
            ordersList,
            filteredOrdersList: ordersList,
            pendingOrdersCount: pendingCount
          });
        } else {
          wx.showToast({
            title: res.result?.message || '获取订单列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('loadOrdersList failed:', err);
        wx.showToast({
          title: '获取订单列表失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ orderLoading: false });
      }
    });
  },

  // 订单搜索输入
  onOrderSearchInput(e) {
    const keyword = e.detail.value.trim();
    this.setData({ orderSearchKeyword: keyword });
    this.loadOrdersList();
  },

  // 清空订单搜索
  onClearOrderSearch() {
    this.setData({ orderSearchKeyword: '' });
    this.loadOrdersList();
  },

  // 筛选订单
  onFilterOrders(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({ orderStatusFilter: status });
    this.loadOrdersList();
  },

  // 接单配送
  onAcceptOrder(e) {
    const orderId = e.currentTarget.dataset.orderId;
    this.updateOrderStatus(orderId, '配送中', '接单成功');
  },

  // 完成配送
  onCompleteOrder(e) {
    const orderId = e.currentTarget.dataset.orderId;
    this.updateOrderStatus(orderId, '已完成', '配送完成');
  },

  // 更新订单状态
  updateOrderStatus(orderId, processStatus, successMessage) {
    wx.showLoading({ title: '处理中...' });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        updateSnacksOrderStatusRequest: {
          orderId: orderId,
          processStatus: processStatus
        }
      },
      success: (res) => {
        console.log('updateOrderStatus result:', res);
        if (res.result?.code === 200) {
          // 重新加载订单列表
          this.loadOrdersList();
          
          wx.showToast({
            title: successMessage,
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.result?.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('updateOrderStatus failed:', err);
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // ==================== 退款相关方法 ====================
  
  // 显示退款弹窗
  onShowRefundModal(e) {
    const orderId = e.currentTarget.dataset.orderId;
    const amount = parseFloat(e.currentTarget.dataset.amount) || 0;
    const status = e.currentTarget.dataset.status;
    const refundReasonFromItem = e.currentTarget.dataset.refundReason || '';
    
    // 检查订单状态，只有已支付的订单才能退款
    if (status === '待支付') {
      wx.showToast({
        title: '待支付订单无法退款',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      showRefundModal: true,
      refundData: {
        orderId: orderId,
        totalAmount: amount,
        orderStatus: status,
        refundType: 'full',
        refundAmount: amount,
        refundReason: refundReasonFromItem,
        rejectReason: ''
      }
    });
  },

  // 隐藏退款弹窗
  onHideRefundModal() {
    this.setData({
      showRefundModal: false,
      refundData: {
        orderId: this.data.refundData.orderId, // 保留订单号，不清空
        totalAmount: 0,
        orderStatus: '',
        refundType: 'full',
        refundAmount: 0,
        refundReason: '',
        rejectReason: ''
      }
    });
  },

  // 选择退款类型
  onSelectRefundType(e) {
    const type = e.currentTarget.dataset.type;
    const refundData = { ...this.data.refundData };
    refundData.refundType = type;
    
    if (type === 'full') {
      refundData.refundAmount = refundData.totalAmount;
    } else {
      refundData.refundAmount = 0;
    }
    
    this.setData({
      refundData: refundData
    });
  },

  // 退款金额输入
  onRefundAmountInput(e) {
    const value = e.detail.value;
    console.log('退款金额输入:', value);
    
    const maxAmount = this.data.refundData.totalAmount;
    
    // 直接保存用户输入的原始值，不进行parseFloat转换
    let finalValue = value;
    
    if (value && value.trim() !== '') {
      // 检查是否是有效的数字格式（包括小数）
      const numberRegex = /^\d*\.?\d*$/;
      if (!numberRegex.test(value)) {
        finalValue = value;
      } else {
        // 如果是有效数字格式，检查是否超过最大值
        const amount = parseFloat(value);
        if (!isNaN(amount) && amount > maxAmount) {
          finalValue = maxAmount.toString();
        } else {
          finalValue = value;
        }
      }
    }
    
    this.setData({
      'refundData.refundAmount': finalValue
    });
  },

  // 退款原因输入
  onRefundReasonInput(e) {
    this.setData({
      'refundData.refundReason': e.detail.value
    });
  },

  // 拒绝原因输入
  onRejectReasonInput(e) {
    this.setData({
      'refundData.rejectReason': e.detail.value
    });
  },

  // 确认退款
  onConfirmRefund() {
    const { orderId, refundType, refundAmount, refundReason, rejectReason, totalAmount } = this.data.refundData;
    
    // 如果是拒绝退款
    if (refundType === 'reject') {
      // 验证拒绝原因
      if (!rejectReason || rejectReason.trim() === '') {
        wx.showToast({
          title: '请输入拒绝原因',
          icon: 'none'
        });
        return;
      }
      
      // 显示确认对话框
      wx.showModal({
        title: '确认拒绝退款',
        content: `确定要拒绝订单 ${orderId} 的退款申请吗？`,
        success: (res) => {
          if (res.confirm) {
            this.processRejectRefund();
          }
        }
      });
      return;
    }
    
    // 原有的退款逻辑
    const refundAmountNum = parseFloat(refundAmount);
    
    // 验证退款金额
    if (refundType === 'partial' && (isNaN(refundAmountNum) || refundAmountNum <= 0)) {
      wx.showToast({
        title: '请输入有效的退款金额',
        icon: 'none'
      });
      return;
    }
    
    if (refundAmountNum > totalAmount) {
      wx.showToast({
        title: '退款金额不能超过订单金额',
        icon: 'none'
      });
      return;
    }
    
    // 显示确认对话框
    const refundTypeText = refundType === 'full' ? '全部退款' : '部分退款';
    wx.showModal({
      title: '确认退款',
      content: `确定要对订单 ${orderId} 进行${refundTypeText}吗？退款金额：¥${refundAmountNum}`,
      success: (res) => {
        if (res.confirm) {
          this.processRefund();
        }
      }
    });
  },

  // 处理退款
  processRefund() {
    const { orderId, refundType, refundAmount, refundReason } = this.data.refundData;
    
    // 确保退款金额是数字类型
    const refundAmountNum = parseFloat(refundAmount);
    
    wx.showLoading({
      title: '处理退款中...'
    });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        processRefundRequest: {
          orderId: orderId,
          refundType: refundType,
          refundAmount: refundAmountNum,
          refundReason: refundReason
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('退款处理结果:', res);
        
        if (res.result && res.result.code === 200) {
          wx.showToast({
            title: '退款处理成功',
            icon: 'success'
          });
          
          // 关闭弹窗
          this.onHideRefundModal();
          
          // 重新加载订单列表
          this.loadOrdersList();
        } else {
          wx.showToast({
            title: res.result?.message || '退款处理失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('退款处理失败:', err);
        wx.showToast({
          title: '退款处理失败',
          icon: 'none'
        });
      }
    });
  },

  // 处理拒绝退款
  processRejectRefund() {
    const { orderId, rejectReason } = this.data.refundData;
    
    wx.showLoading({
      title: '处理中...'
    });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        handleRejectRefundRequest: {
          orderId: orderId,
          rejectReason: rejectReason
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('拒绝退款处理结果:', res);
        
        if (res.result && res.result.code === 200) {
          wx.showToast({
            title: '拒绝退款成功',
            icon: 'success'
          });
          
          // 关闭弹窗
          this.onHideRefundModal();
          
          // 重新加载订单列表
          this.loadOrdersList();
        } else {
          wx.showToast({
            title: res.result?.message || '拒绝退款失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('拒绝退款处理失败:', err);
        wx.showToast({
          title: '拒绝退款失败',
          icon: 'none'
        });
      }
    });
  }
})